﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;

namespace Api.Common
{
    public class BoolConverter : JsonConverter
    {
        /// <summary>
        /// 这里是关键点1
        /// </summary>
        /// <param name="objectType"></param>
        /// <returns></returns>
        public override bool CanConvert(Type objectType)
        {
            return (objectType == typeof(bool));
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var result = Convert((bool)value);
            JToken.FromObject(result).WriteTo(writer);
        }
        /// <summary>
        /// 将bool类型转化为0，1
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private byte Convert(bool? flag)
        {
            if (flag.HasValue)
            {
                if (flag.Value) return 1;
            }
            return 0;
        }


    }
}